package com.zjitc.book.service.impl;

import com.zjitc.book.entity.MyUserDetails;
import com.zjitc.book.entity.Permissions;
import com.zjitc.book.entity.User;
import com.zjitc.book.mapper.UserMapper;
import com.zjitc.book.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserDetailsService, UserInfoService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.getUserByUsername(username);
        if(user == null){
            throw new UsernameNotFoundException("无法找到用户");
        }
        List<String> authorities = userMapper.getPermissionsByUsername(username);
        MyUserDetails userDetails = new MyUserDetails(user,authorities);
        return userDetails;
    }

    @Override
    public List<Permissions> getMenu() {
        String username = (String)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<Permissions> menu = userMapper.getMenu(username);



        System.out.println(menu);
        return menu;
    }

    private List<Permissions> createTreeMenu(List<Permissions> menus){
        List<Permissions> rootMenus = new ArrayList<>();
        Map<Integer, Permissions> maps = new HashMap<>();
        menus.forEach(menu->{
            maps.put(menu.getId(), menu);
        });

        return rootMenus;
    }
}
